package com.yuhanginfo.modules.web.util;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.UnavailableSecurityManagerException;
import org.apache.shiro.session.InvalidSessionException;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.yuhanginfo.common.utils.CacheUtils;
import com.yuhanginfo.common.utils.SpringContextHolder;
import com.yuhanginfo.modules.web.dao.WebYongUserDao;
import com.yuhanginfo.modules.web.entity.WebYongUser;

/**
 * 用户工具类
 * @author YuHangInfo
 * @version 2013-12-05
 */
public class WebUserUtils {

	private WebUserUtils(){}
	private static WebYongUserDao webYongUserDao = SpringContextHolder.getBean(WebYongUserDao.class);
	private static Logger log = LoggerFactory.getLogger(WebUserUtils.class);
	public static final String YONGUSER_CACHE = "yongUserCache";
	public static final String YONGUSER_CACHE_ID = "yid_";
	public static final String YONGUSER_CACHE_LOGIN_NAME = "yln";
	public static final String USER_CACHE_LIST_BY_OFFICE_ID = "oid_";
	
	public static final String CACHE_AUTH_INFO = "authInfo";
	public static final String CACHE_ROLE_LIST = "roleList";
	public static final String CACHE_STORE_LIST = "storeList";
	public static final String CACHE_MENU_LIST = "menuList";
	public static final String CACHE_AREA_LIST = "areaList";
	public static final String CACHE_OFFICE_LIST = "officeList";
	public static final String CACHE_OFFICE_ALL_LIST = "officeAllList";
	
	/**
	 * 根据ID获取用户
	 * @param id
	 * @return 取不到返回null
	 */
	public static WebYongUser getYong(String id){
		WebYongUser user = (WebYongUser)CacheUtils.get(YONGUSER_CACHE, YONGUSER_CACHE_ID + id);
		if (user ==  null){
			user = webYongUserDao.get(id);
			if (user == null){
				return null;
			}
			CacheUtils.put(YONGUSER_CACHE, YONGUSER_CACHE_ID + user.getId(), user);
			CacheUtils.put(YONGUSER_CACHE, YONGUSER_CACHE_ID + user.getLoginName(), user);
		}
		return user;
	}
	
	public static WebYongUser getNoCacheYong(String id){
		WebYongUser user = webYongUserDao.get(id);
		if (user == null){
			return null;
		}
		CacheUtils.put(YONGUSER_CACHE, YONGUSER_CACHE_ID + user.getId(), user);
		CacheUtils.put(YONGUSER_CACHE, YONGUSER_CACHE_ID + user.getLoginName(), user);
		return user;
	}
	
	/**
	 * 根据登录名获取一般用户
	 * @param loginName
	 * @return 取不到返回null
	 */
	public static WebYongUser getByYongLoginName(String loginName){
		WebYongUser user = (WebYongUser)CacheUtils.get(YONGUSER_CACHE, YONGUSER_CACHE_LOGIN_NAME + loginName);
		if (user == null){
			user = webYongUserDao.getByLoginName(new WebYongUser(null, loginName));
			if (user == null){
				return null;
			}
			CacheUtils.put(YONGUSER_CACHE, YONGUSER_CACHE_ID + user.getId(), user);
			CacheUtils.put(YONGUSER_CACHE, YONGUSER_CACHE_LOGIN_NAME + user.getLoginName(), user);
		}
		return user;
	}
	
	/**
	 * 清除当前用户缓存
	 */
	public static void clearCache(){
		removeCache(CACHE_AUTH_INFO);
		removeCache(CACHE_ROLE_LIST);
		removeCache(CACHE_MENU_LIST);
		removeCache(CACHE_AREA_LIST);
		removeCache(CACHE_OFFICE_LIST);
		removeCache(CACHE_OFFICE_ALL_LIST);
		WebUserUtils.clearWebCache(getYongUser());
	}
	
	/**
	 * 清除指定用户缓存
	 * @param user
	 */
	public static void clearWebCache(WebYongUser user){
		CacheUtils.remove(YONGUSER_CACHE, YONGUSER_CACHE_ID + user.getId());
		CacheUtils.remove(YONGUSER_CACHE, YONGUSER_CACHE_LOGIN_NAME + user.getLoginName());
		CacheUtils.remove(YONGUSER_CACHE, YONGUSER_CACHE_LOGIN_NAME + user.getOldLoginName());
	}
	

	/**
	 * 获取当前用户
	 * @return 取不到返回 new YongUser()
	 */
	public static WebYongUser getYongUser(){
		com.yuhanginfo.modules.web.security.UserRealm.Principal principal = getUserPrincipal();
		if (principal!=null){
			WebYongUser user = getYong(principal.getId());
			if (user != null){
				return user;
			}
			return new WebYongUser();
		}
		// 如果没有登录，则返回实例化空的User对象。
		return new WebYongUser();
	}
	
	/**
	 * 获取授权主要对象
	 */
	public static Subject getSubject(){
		return SecurityUtils.getSubject();
	}
	
	/**
	 * 获取当前管理员登录者对象
	 */
	public static com.yuhanginfo.modules.web.security.AdminRealm.Principal getAdminPrincipal(){
		try{
			Subject subject = SecurityUtils.getSubject();
			com.yuhanginfo.modules.web.security.AdminRealm.Principal principal = (com.yuhanginfo.modules.web.security.AdminRealm.Principal)subject.getPrincipal();
			if (principal != null){
				return principal;
			}
		}catch (UnavailableSecurityManagerException e) {
			log.error(e.getMessage(),e);
		}catch (InvalidSessionException e){
			log.error(e.getMessage(),e);
		}
		return null;
	}
	
	/**
	 * 获取当前一般登录者对象
	 */
	public static com.yuhanginfo.modules.web.security.UserRealm.Principal getUserPrincipal(){
		try{
			Subject subject = SecurityUtils.getSubject();
			com.yuhanginfo.modules.web.security.UserRealm.Principal principal = (com.yuhanginfo.modules.web.security.UserRealm.Principal)subject.getPrincipal();
			if (principal != null){
				return principal;
			}
		}catch (UnavailableSecurityManagerException e) {
			log.error(e.getMessage(),e);
		}catch (InvalidSessionException e){
			log.error(e.getMessage(),e);
		}
		return null;
	}
	
	public static Session getSession(){
		try{
			Subject subject = SecurityUtils.getSubject();
			Session session = subject.getSession(false);
			if (session == null){
				session = subject.getSession();
			}
			if (session != null){
				return session;
			}
		}catch (InvalidSessionException e){
			log.error(e.getMessage(),e);
		}
		return null;
	}
	
	// ============== User Cache ==============
	
	public static Object getCache(String key) {
		return getCache(key, null);
	}
	
	public static Object getCache(String key, Object defaultValue) {
		Object obj = getSession().getAttribute(key);
		return obj==null?defaultValue:obj;
	}

	public static void putCache(String key, Object value) {
		getSession().setAttribute(key, value);
	}

	public static void removeCache(String key) {
		getSession().removeAttribute(key);
	}
	
}
